<script setup lang="ts">
  import { computed, ref, watch } from 'vue'
  import {
    useGetReceiverType,
    useReceiverTypeForm,
    useGetReceiverTypeOptions,
  } from '@/services/pages/note/template'
  import useGetSpecifyPersonOptions from '@/services/pages/common/specify-person-options'
  import { FormInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'

  const { receiverType, getReceiverTypeLoading, getReceiverTypeBySmsTemplateId } =
    useGetReceiverType()
  const {
    receiverTypeOptions,
    getReceiverTypeOptionsLoading,
    getReceiverTypeOptionsBySmsTemplateId,
  } = useGetReceiverTypeOptions()
  const { receiverTypeForm, saveReceiverTypeLoading, saveReceiverType } = useReceiverTypeForm()
  const {
    specifyPersonOptions,
    getSpecifyPersonOptionsLoading,
    getSpecifyPersonOptionsKeyword,
    getSpecifyPersonOptions,
  } = useGetSpecifyPersonOptions()

  defineOptions({
    name: 'SmsReceiverTypeUpdate',
  })

  const props = defineProps({
    smsTemplateId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'updated'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 验证规则
  const rules = ref({
    roleTypes: [{ required: true, message: '请选择人员类型', trigger: ['change', 'blur'] }],
    empIds: [{ required: false, message: '请选择人员', trigger: ['change', 'blur'] }],
  })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 加载
  const dialogLoading = computed(() => {
    return getReceiverTypeLoading.value || saveReceiverTypeLoading.value
  })

  /**
   * 接收者类型更新事件
   */
  const onChangeReceiverType = () => {
    if (receiverTypeForm.value.roleTypes.includes('2')) {
      getSpecifyPersonOptions()
      rules.value.empIds[0].required = true
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    receiverTypeForm.value.empIds = []
    receiverTypeForm.value.roleTypes = []
    visible.value = false
  }

  /**
   * 保存事件
   */
  const onConfirm = async () => {
    if (formInstance.value) {
      await formInstance.value.validate((valid) => {
        if (valid) {
          saveReceiverType(props.smsTemplateId).then((res) => {
            if (res.code === 20000) {
              HMessage.success(infoTip.sms.template.updateReceiverTypeSuccess)
              onCancel()
              emits('updated')
            } else {
              HMessageBox.error(res.message)
            }
          })
        }
      })
    }
  }

  watch(
    visible,
    (value) => {
      if (value) {
        if (props.smsTemplateId) {
          getReceiverTypeBySmsTemplateId(props.smsTemplateId).then(() => {
            receiverTypeForm.value.empIds = receiverType.value.empIds
            if (receiverType.value.roleTypes) {
              receiverTypeForm.value.roleTypes = receiverType.value.roleTypes.map((item) =>
                item.toString(),
              )
              if (receiverTypeForm.value.roleTypes.includes('2')) {
                onChangeReceiverType()
              } else {
                rules.value.empIds[0].required = false
              }
            }
          })
        }
        getReceiverTypeOptionsBySmsTemplateId(props.smsTemplateId)
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-dialog v-model="visible" title="修改人员类型" :loading="dialogLoading" :width="800">
    <el-form
      ref="formInstance"
      label-position="top"
      inline-message
      class="modal_form_content"
      :rules="rules"
      :model="receiverTypeForm"
    >
      <el-form-item label="人员类型" prop="roleTypes">
        <el-select
          v-model="receiverTypeForm.roleTypes"
          :loaidng="getSpecifyPersonOptionsLoading"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="5"
          @change="onChangeReceiverType"
        >
          <el-option
            v-for="(receiverType, receiverTypeIndex) in receiverTypeOptions"
            :key="receiverTypeIndex"
            :value="receiverType.id"
            :label="receiverType.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="指定人员" prop="empIds">
        <el-select
          v-model="receiverTypeForm.empIds"
          multiple
          :disabled="!receiverTypeForm.roleTypes.includes('2')"
          :loading="getReceiverTypeOptionsLoading"
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="5"
        >
          <template #header>
            <div class="select-header">
              <el-input
                v-model.trim="getSpecifyPersonOptionsKeyword"
                placeholder="请输入关键字"
                @keyup.enter="getSpecifyPersonOptions"
              />
              <h-plain-button @click="getSpecifyPersonOptions">搜索</h-plain-button>
            </div>
          </template>
          <el-option
            v-for="(person, personIndex) in specifyPersonOptions"
            :key="personIndex"
            :value="person.id"
            :label="person.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="onCancel">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  .select-header {
    display: flex;
    column-gap: 5px;
  }
</style>
